﻿package com.agileai.miscdp.hotweb.ui.editors.treecontent;

import java.io.StringWriter;
import java.util.List;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;

import com.agileai.miscdp.hotweb.domain.BaseFuncModel;
import com.agileai.miscdp.hotweb.domain.ListTabColumn;
import com.agileai.miscdp.hotweb.domain.PageFormField;
import com.agileai.miscdp.hotweb.domain.PageParameter;
import com.agileai.miscdp.hotweb.domain.treecontent.ContentTableInfo;
import com.agileai.miscdp.hotweb.domain.treecontent.TreeContentFuncModel;
import com.agileai.miscdp.hotweb.ui.editors.BaseModelEditor;
import com.agileai.miscdp.hotweb.ui.views.TreeObject;
import com.agileai.miscdp.util.DialogUtil;
import com.agileai.miscdp.util.MiscdpUtil;
import com.agileai.hotweb.model.EditTableType;
import com.agileai.hotweb.model.ListTableType;
import com.agileai.hotweb.model.QueryBarType;
import com.agileai.hotweb.model.treecontent.TreeContentFuncModelDocument;
import com.agileai.hotweb.model.treecontent.TreeContentFuncModelDocument.TreeContentFuncModel.BaseInfo;
import com.agileai.hotweb.model.treecontent.TreeContentFuncModelDocument.TreeContentFuncModel.BaseInfo.ContentTableInfo.TableMode;
import com.agileai.hotweb.model.treecontent.TreeContentFuncModelDocument.TreeContentFuncModel.ContentEditView;
import com.agileai.hotweb.model.treecontent.TreeContentFuncModelDocument.TreeContentFuncModel.ContentListTabArea;
import com.agileai.util.FileUtil;
import com.agileai.util.StringUtil;
/**
 * 树及内容功能模型编辑器
 */
public class TreeContentModelEditor extends BaseModelEditor{
	private TACBasicConfigPage tacBasicConfigPage;
	private TACContentsCfgPage tacContentsCfgPage;
	
    public void init(IEditorSite site, IEditorInput input) throws PartInitException {
        setSite(site);
        setInput(input);
        setPartName(input.getName());
		init();
		ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
    }
	private void init() {
		funcModel = (TreeContentFuncModel)this.getEditorInput();
	}

	protected void createPages() {
		tacBasicConfigPage = new TACBasicConfigPage(getContainer(),this,SWT.NONE);
		tacContentsCfgPage = new TACContentsCfgPage(getContainer(),this,SWT.NONE);
		
		String basicConfig = MiscdpUtil.getIniReader().getValue("EditorInfo","BasicInfo");
		int basicConfigIndex = addPage(tacBasicConfigPage);
		setPageText(basicConfigIndex,basicConfig);
		
		String tablJspConfig = MiscdpUtil.getIniReader().getValue("EditorInfo","TabContentInfo");
		int listJspCfgIndex = addPage(tacContentsCfgPage);
		setPageText(listJspCfgIndex,tablJspConfig);
		
		initValues();
		
		tacBasicConfigPage.registryModifier();
	}
	
	public void doSave(IProgressMonitor monitor) {
		try {
			TreeContentFuncModel treeContentFuncModel = buildFuncModel();
	    	String projectName = treeContentFuncModel.getProjectName();
	    	String treeTableName = treeContentFuncModel.getTreeTableName();
	    	if (StringUtil.isNullOrEmpty(treeTableName)){
	    		String sqlCheckNullMsg = MiscdpUtil.getIniReader().getValue("TreeContentModelEditor","TreeTableNameCheckNullMsg");
	    		DialogUtil.showInfoMessage(sqlCheckNullMsg);
	    		return;
	    	}
	    	
	    	String listJspName = treeContentFuncModel.getListJspName();
	    	if (StringUtil.isNullOrEmpty(listJspName)){
	    		String sqlCheckNullMsg = MiscdpUtil.getIniReader().getValue("TreeContentModelEditor","ListJspCheckNullMsg");
	    		DialogUtil.showInfoMessage(sqlCheckNullMsg);
	    		return;
	    	}
	    	
	    	TreeContentFuncModelDocument funcModelDocument = (TreeContentFuncModelDocument)buildFuncModelDocument(treeContentFuncModel);
			StringWriter writer = new StringWriter();
			funcModelDocument.save(writer);
			String funcName = treeContentFuncModel.getFuncName();
			String funcSubPkg = treeContentFuncModel.getFuncSubPkg();
			
			String funcDefine = writer.toString();
			String funcId = treeContentFuncModel.getFuncId();
			String fileName = MiscdpUtil.getFuncFileName(projectName,funcId);
			FileUtil.writeFile(fileName, funcDefine);
			
			this.isModified = false;
			firePropertyChange(PROP_DIRTY);
			
			TreeViewer funcTreeViewer = funcModelTree.getFuncTreeViewer();
			ISelection selection = funcTreeViewer.getSelection();
			Object obj = ((IStructuredSelection) selection).getFirstElement();
			TreeObject treeObject = null;
			if (obj instanceof TreeObject) {
				treeObject = (TreeObject) obj;
				treeObject.setName(funcName);
				treeObject.setFuncSubPkg(funcSubPkg);
			}

			updateIndexFile(projectName);
			this.setPartName(funcName);
			funcTreeViewer.refresh();
			try {
		    	IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
		    	treeContentFuncModel.buildFuncModel(funcDefine);
				project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
			} catch (CoreException e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public TACBasicConfigPage getBasicConfigPage() {
		return tacBasicConfigPage;
	}
	public TACContentsCfgPage getContentsCfgPage() {
		return tacContentsCfgPage;
	}
	public TreeContentFuncModel buildFuncModel() {
		this.tacBasicConfigPage.buildConfig();
		return this.tacContentsCfgPage.buildConfig();
	}
	public void initValues() {
		this.tacBasicConfigPage.initValues();
	}
	public TreeContentFuncModel getFuncModel() {
		return (TreeContentFuncModel)funcModel;
	}
	public Object buildFuncModelDocument(BaseFuncModel baseFuncModel){
		TreeContentFuncModel treeContentFuncModel = (TreeContentFuncModel)baseFuncModel;
		TreeContentFuncModelDocument funcModelDocument = TreeContentFuncModelDocument.Factory.newInstance();
		TreeContentFuncModelDocument.TreeContentFuncModel funcModel = funcModelDocument.addNewTreeContentFuncModel();
		TreeContentFuncModelDocument.TreeContentFuncModel.BaseInfo baseInfo = funcModel.addNewBaseInfo();
		String treeTableName = treeContentFuncModel.getTreeTableName();
		String listJspName = treeContentFuncModel.getListJspName();
		String treePickJspName = treeContentFuncModel.getTreePickJspName();
		String treeEditJspName = treeContentFuncModel.getTreeEditJspName();
		
		baseInfo.setTemplate(treeContentFuncModel.getTemplate());
		baseInfo.setMainListJspName(listJspName);
		baseInfo.setRootColumnId(treeContentFuncModel.getRootColumnId());
		baseInfo.setColumnIdField(treeContentFuncModel.getColumnIdField());
		baseInfo.setColumnNameField(treeContentFuncModel.getColumnNameField());
		baseInfo.setColumnParentIdField(treeContentFuncModel.getColumnParentIdField());
		baseInfo.setColumnSortField(treeContentFuncModel.getColumnSortField());
		baseInfo.setTreeTableName(treeTableName);
		baseInfo.setTreePickJspName(treePickJspName);
		baseInfo.setTreeEditJspName(treeEditJspName);
		
		baseInfo.setIsManageTree(treeContentFuncModel.isManageTree());
		baseInfo.setTreeEditMode(TreeContentFuncModelDocument.TreeContentFuncModel.BaseInfo.TreeEditMode.Enum.forString(treeContentFuncModel.getTreeEditMode()));
		
		TreeContentFuncModelDocument.TreeContentFuncModel.BaseInfo.Service service = baseInfo.addNewService();
		String interfaceName = treeContentFuncModel.getInterfaceName();
		service.setServiceId(treeContentFuncModel.getServiceId());
		service.setImplClassName(treeContentFuncModel.getImplClassName());
		service.setInterfaceName(interfaceName);
		
		String selectTreeHandlerId = treePickJspName.substring(0,treePickJspName.length()-4);
		selectTreeHandlerId = selectTreeHandlerId.substring(selectTreeHandlerId.lastIndexOf("/")+1,selectTreeHandlerId.length());
		
		String treeEditHandlerId = treeEditJspName.substring(0,treeEditJspName.length()-4);
		treeEditHandlerId = treeEditHandlerId.substring(treeEditHandlerId.lastIndexOf("/")+1,treeEditHandlerId.length());
		
		String listHandlerId = listJspName.substring(0,listJspName.length()-4);
		listHandlerId = listHandlerId.substring(listHandlerId.lastIndexOf("/")+1,listHandlerId.length());
		
		String tempClassPath = interfaceName.substring(0,interfaceName.lastIndexOf(".")).replace("bizmoduler","controller"); 
		String listHandlerClass = tempClassPath + "." + listHandlerId + "Handler";
		String selectTreeHandlerClass = tempClassPath + "." + selectTreeHandlerId + "Handler";
		String treeEditHandlerClass = tempClassPath + "." + treeEditHandlerId + "Handler";
		
		TreeContentFuncModelDocument.TreeContentFuncModel.BaseInfo.Handler handler = baseInfo.addNewHandler();
		handler.setSelectTreeHandlerId(selectTreeHandlerId);
		handler.setSelectTreeHandlerClass(selectTreeHandlerClass);
		handler.setListHandlerId(listHandlerId);
		handler.setListHandlerClass(listHandlerClass);
		handler.setTreeEditHandlerId(treeEditHandlerId);
		handler.setTreeEditHandlerClass(treeEditHandlerClass);
		
		TreeContentFuncModelDocument.TreeContentFuncModel.BaseInfo.SqlResource sqlResource = baseInfo.addNewSqlResource();
		
		sqlResource.setSqlNameSpace(interfaceName.toLowerCase());
		String sqlMapPath = "sqlmap/"+interfaceName+".xml";;
		sqlResource.setSqlMapPath(sqlMapPath);
		
		
		String projectName = this.getFuncModel().getProjectName();
		List<ContentTableInfo> contentTableInfoList = treeContentFuncModel.getContentTableInfoList();
		for (int i=0;i < contentTableInfoList.size();i++){
			ContentTableInfo ctInfoModel = contentTableInfoList.get(i);
			String tabId = ctInfoModel.getTabId();
			BaseInfo.ContentTableInfo contentTableInfo = baseInfo.addNewContentTableInfo();
			contentTableInfo.setQueryListSql(ctInfoModel.getQueryListSql());
			contentTableInfo.setTabId(tabId);
			String tabName = ctInfoModel.getTabName();
			contentTableInfo.setTabName(tabName);
			contentTableInfo.setTableName(ctInfoModel.getTableName());
			String tableMode = ctInfoModel.getTableMode();
			contentTableInfo.setTableMode(TableMode.Enum.forString(tableMode));
			String primaryKey = ctInfoModel.getPrimaryKey(projectName);
			contentTableInfo.setPrimaryKey(primaryKey);
			contentTableInfo.setColField(ctInfoModel.getColField());
			contentTableInfo.setRelTableName(ctInfoModel.getRelTableName());
			
			List<PageFormField> pagetFormFields = treeContentFuncModel.getContentEditFormFieldsMap().get(tabId);
			ContentEditView contentEditView = funcModel.addNewContentEditView();
			contentEditView.setTabId(tabId);

			EditTableType editTableType = contentEditView.addNewDetailEditArea();
			this.processEditTableType(editTableType, pagetFormFields);
			
			String contentEditJspName = listJspName.substring(0,listJspName.indexOf(".jsp"))+tabId+"Edit"+".jsp";
			String contentEditHandlerId = tabId+"Edit";
			String contentEditHandlerClass = listHandlerClass.substring(0,listHandlerClass.lastIndexOf("."))+"."+tabId+"EditHandler";
			contentEditView.setTabId(tabId);
			contentEditView.setJspName(contentEditJspName);
			contentEditView.setHandlerId(contentEditHandlerId);
			contentEditView.setHandlerClass(contentEditHandlerClass);
			
			List<ListTabColumn> listTabColumns = treeContentFuncModel.getContentListTableColumnsMap().get(tabId);
			List<PageParameter> pageParameters = treeContentFuncModel.getContentPageParametersMap().get(tabId);
			
			ContentListTabArea contentListTabArea = funcModel.addNewContentListTabArea();
			contentListTabArea.setTabId(tabId);
			contentListTabArea.setTabName(tabName);
			
			QueryBarType queryBarType = contentListTabArea.addNewParameterArea(); 
			this.processQueryBarType(queryBarType, pageParameters);
			ListTableType listTableType = contentListTabArea.addNewListTableArea();
			this.processListTableType(listTableType, listTabColumns, primaryKey);
		}
		
		if (treeContentFuncModel.isManageTree()){
			TreeContentFuncModelDocument.TreeContentFuncModel.TreeEditView treeEditView = funcModel.addNewTreeEditView();
			EditTableType editTableType = treeEditView.addNewTreeEditArea();
			this.processEditTableType(editTableType, treeContentFuncModel.getTreeEditFormFields());
		}
		return funcModelDocument;
	}
}